package org.summerframework.component.security.core.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.summerframework.component.security.AdminSave;
import org.summerframework.component.security.core.filter.RequestParamFilter;
import org.summerframework.component.security.core.handle.UserIdRequestParamHandle;
import org.summerframework.component.security.core.interceptor.CheckUserPermissionInterceptor;
import org.summerframework.component.security.core.interceptor.RequestContextInterceptor;
import org.summerframework.component.security.core.interceptor.SecurityInterceptor;
import org.summerframework.component.security.core.service.LoginManage;
import org.summerframework.component.security.core.util.useragent.UADeviceJsUtil;

/**
 * @author 石超
 * @version v1.0.0
 */
@Configuration
@EnableConfigurationProperties({LoginProperties.class})
@ConditionalOnBean(LoginManage.class)
public class SecurityAutoConfiguration {

    @Bean
    public RequestContextInterceptor requestContextInterceptor() {
        return new RequestContextInterceptor();
    }

    @Bean
    public CheckUserPermissionInterceptor checkUserPermissionInterceptor() {
        return new CheckUserPermissionInterceptor();
    }

    @Bean
    @ConditionalOnMissingClass("org.springframework.security.core.Authentication")
    public SecurityInterceptor securityInterceptor() {
        return new SecurityInterceptor();
    }

    @Bean
    public RequestParamFilter userFilter(RequestMappingHandlerMapping requestMappingHandlerMapping, RequestContextInterceptor requestContextInterceptor) {
        return new RequestParamFilter(requestMappingHandlerMapping, requestContextInterceptor);
    }

    @Bean("userIdRequestParamHandle")
    @ConditionalOnMissingBean(name = "userIdRequestParamHandle")
    public UserIdRequestParamHandle userIdRequestParamHandle() {
        return new UserIdRequestParamHandle();
    }

    @Bean
    public UADeviceJsUtil uaDeviceJsUtil() {
        UADeviceJsUtil uaDeviceJsUtil = new UADeviceJsUtil();
        UADeviceJsUtil.parse("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
        return uaDeviceJsUtil;
    }

    @Bean
    @ConditionalOnMissingBean(AdminSave.class)
    public AdminSave adminSave(LoginProperties loginProperties) {
        return loginProperties.getAdminSave();
    }
}
